package cn.javabb.core.service.blog;

import cn.hutool.http.HtmlUtil;
import cn.javabb.common.exception.ForbiddenException;
import cn.javabb.common.utils.ListUtils;
import cn.javabb.core.base.BaseService;
import cn.javabb.core.constant.BizConstant;
import cn.javabb.core.entity.biz.ContentDO;
import cn.javabb.core.entity.blog.BlogDO;
import cn.javabb.core.mapper.blog.BlogMapper;
import cn.javabb.core.model.StatusEnum;
import cn.javabb.core.model.biz.PublishDateModel;
import cn.javabb.core.query.BlogQuery;
import cn.javabb.core.service.biz.CommentService;
import cn.javabb.core.service.biz.ContentService;
import cn.javabb.core.service.sys.SysConfigService;
import cn.javabb.core.service.sys.UserService;
import cn.javabb.core.util.ShiroUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @desc:
 * @author: javabb (javabob(a)163.com)
 * @create: 2019/12/01 18:18
 */
@Service
public class BlogService extends BaseService<BlogDO> {
    @Autowired
    private BlogMapper blogMapper;
    @Autowired
    private ContentService contentService;
    @Autowired
    private CommentService commentService;
    @Autowired
    private UserService userService;
    @Autowired
    private SysConfigService configService;
    /**
     * 分页查询
     * @param query
     * @return
     */
    public PageInfo<BlogDO> queryPage(BlogQuery query) {
        PageHelper.startPage(query.getPage(), query.getSize());
        List<BlogDO> listBlogs = blogMapper.list(query);
        PageInfo p = new PageInfo(listBlogs);
        return p;
    }
    /**
     * 查询
     * @param blogId
     * @return
     */
    public BlogDO get(Integer blogId) {
        BlogDO blog = blogMapper.get(blogId);
        if (blog == null) {
            return null;
        }
        blog.getAuthor().setIsAdmin(userService.isAdmin(blog.getAuthor().getId()));
        return blog;
    }
    /**
     * 保存博客
     * @param blog
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public boolean save(BlogDO blog) {
        if (blog.getBlogId() != null) {
            // 编辑 判断能否编辑
            BlogDO b = this.queryById(blog.getBlogId());
            if (b == null) {
                return false;
            }else if(b.getUserId()!=ShiroUtil.getLoginUser().getId()){
                throw new ForbiddenException("参数错误，当前登录用户不是博客作者");
            }

        }
        // 保存博客内容
        ContentDO content = new ContentDO();
        String contentText = HtmlUtil.cleanHtmlTag(blog.getContent());
        content.setContentHtml(blog.getContent())
                .setContentText(contentText)
                .setContentId(blog.getContentId());
        contentService.insertOrUpdateSelective(content);
        // 保存博客
        blog.setBlogDesc(contentText.length() > 120 ? contentText.substring(0, 120) : contentText);
        blog.setUserId(ShiroUtil.getLoginUser().getId());
        blog.setContentId(content.getContentId());
        this.insertOrUpdateSelective(blog);

        return true;
    }

    /**
     * 删除
     * @param ids
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public boolean delete(String ids) {
        List<String> idList = ListUtils.stringToListString(ids);
        int num = 0;
        for (String id : idList) {
            BlogDO blog = this.queryById(id);
            // 删除博客
            num += this.deleteById(id);
            // 删除博客内容
            contentService.deleteById(blog.getContentId());
            // 删除博客评论
            commentService.deleteByArticleId(Integer.parseInt(id), BizConstant.ARTICLE_TYPE_BLOG);
        }
        return num>0?true:false;
    }
    /**
     * 更新状态
     * @param ids
     * @param state
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public boolean updateState(String ids, Integer state) {
        List<String> idList = ListUtils.stringToListString(ids);
        Example ex = new Example(BlogDO.class);
        ex.createCriteria().andIn("blogId", idList);
        BlogDO blog = new BlogDO();
        blog.setState(state);
        return this.blogMapper.updateByExampleSelective(blog, ex)>0?true:false;
    }
    /**
     * 更新状态
     * @param ids
     * @param top
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public boolean updateTop(String ids, Boolean top) {
        List<String> idList = ListUtils.stringToListString(ids);
        Example ex = new Example(BlogDO.class);
        ex.createCriteria().andIn("blogId", idList);
        BlogDO blog = new BlogDO();
        blog.setBlogTop(top);
        return this.blogMapper.updateByExampleSelective(blog, ex)>0?true:false;
    }
    /**
     * 更新状态
     * @param ids
     * @param support
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public boolean updateSupport(String ids, Boolean support) {
        List<String> idList = ListUtils.stringToListString(ids);
        Example ex = new Example(BlogDO.class);
        ex.createCriteria().andIn("blogId", idList);
        BlogDO blog = new BlogDO();
        blog.setBlogSupport(support);
        return this.blogMapper.updateByExampleSelective(blog, ex)>0?true:false;
    }

    /**
     * 根据类型ID删除
     * @param typeId
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public boolean deleteByTypeId(Integer typeId) {
        BlogDO blog = new BlogDO().setTypeId(typeId);
        List<BlogDO> list = this.queryListByWhere(blog);
        String ids = list.stream().map(x->String.valueOf(x.getBlogId())).collect(Collectors.joining(","));
        // 删除博客
        return this.delete(ids);
    }
    /*删除用户博客*/
    public boolean deleteByUserId(Integer userId) {
        BlogDO blog = new BlogDO().setUserId(userId);
        List<BlogDO> list = this.queryListByWhere(blog);
        String ids = list.stream().map(x->String.valueOf(x.getBlogId())).collect(Collectors.joining(","));
        // 删除博客
        return this.delete(ids);
    }
    /**
     * 博客归档
     * @return
     */
    public List<PublishDateModel> listPublishDates(){
        return blogMapper.listByPublishDate();
    }

    /**
     * 校验能否被评论
     * @param blogId
     * @return
     */
    public boolean checkCommentAble(Integer blogId) {
        if (!configService.getGobalCommentState()) {
            return false;
        }
        BlogDO blog = new BlogDO().setBlogId(blogId).setCommentState(true).setState(StatusEnum.NORMAL.getCode());
        return this.queryCountByWhere(blog) > 0;
    }
}
